package com.meter.reading.util;

import com.meter.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;

/**
 * redis定时任务
 */
@Slf4j
public class RedisRunnable implements Runnable {

    private CountDownLatch countDownLatch;

    private RedisService redisService;

    private String key;

    private int max;

    public RedisRunnable(CountDownLatch countDownLatch, RedisService redisService, String key, int max){
        this.countDownLatch = countDownLatch;
        this.key = key;
        this.redisService = redisService;
        this.max = max;
    }

    @Override
    public void run(){
        int count = 1;
        while (true){
            try{
                if(redisService.hasKey(key)){
                    Thread.sleep(1000);
                }else{
                    if(countDownLatch != null){
                        countDownLatch.countDown();
                    }
                    break;
                }

            } catch (Exception e){
                redisService.del(key);
                if(countDownLatch != null){
                    countDownLatch.countDown();
                }
                break;
            } finally {
                count ++;
                if(count > max){
                    redisService.del(key);
                    if (countDownLatch != null) {
                        countDownLatch.countDown();
                    }
                    break;
                }
            }
        }
    }
}
